package com.cahnggou.web.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.pay.feign.PayFeign;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-26 11:18
 */
@Controller
@RequestMapping("/wxpay")
public class PayController {

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private PayFeign payFeign;


    /**
     *  返回二维码支付界面
     * @param parameterMap
     * @param model
     * @return
     */
    @GetMapping
    public String wxpay(@RequestParam Map<String,String> parameterMap, Model model){

        String orderId = parameterMap.get("orderId");
        Result orderResult = orderFeign.findById(orderId);
        ObjectMapper mapper = new ObjectMapper();
        Order order = mapper.convertValue(orderResult.getData(), Order.class);
        if (order==null){   //如果订单不存在
            return "fail";
        }
        if (!"0".equals(order.getPayStatus())){ //如果不是未支付订单
            return "fail";
        }

        //获取二维码生成的返回结果
        Result payResult = payFeign.nativePay(parameterMap);
        if (payResult.getData()==null){
            return "fail";  //生成二维码出错
        }
        Map payMap = (Map) payResult.getData();
        payMap.put("payMoney","1");
        payMap.put("orderId",orderId);
        model.addAllAttributes(payMap);
        return "wxpay";
    }
}
